<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter Cny Library
 *
 * @package         CodeIgniter
 * @subpackage      Libraries
 * @category        Libraries
 * @author          Eason
 * @license         MIT
 */
class Cny_Class {
    protected $ci;
    private $redis;
    private $db;
    private $log_db;
    private $object = 'cny';
    public function __construct() {
        $this->ci = & get_instance();
        //链接redis
        $this->ci->load->driver('cache');
        $this->ci->cache->redis->is_supported();
        $this->redis = $this->ci->cache->redis;

        $this->db = $this->ci->load->database('default',true);
        $this->log_db = $this->ci->load->database('log',true);
    }

    /**
     * 加
     * @param array  $data_arr [description]
     * @param int  $dot 保留位数
     * @param boolean $addMax  是否变更max_transfer
     * @param string  $write_conn [description]
     */
    public function add($data_arr, $dot=2) {
        foreach ($data_arr as $key => $val) {
            $$key = $val;
        }
        unset($data_arr);
        $rs = false;
        $datetime = date('Y-m-d H:i:s');
        if(!isset($table) || $table=='') $table = 'user_info';
        if(!isset($ip) || $ip=='') $ip = '127.0.0.1';
        if(!isset($where) || $where=='') $where = array('uid'=>$uid);
        try {
            $this->db->set($this->object, $this->object.'+'.$use_value, FALSE);
            // $this->db->set($this->object.'_block', $this->object.'_block-'.$use_value, FALSE);
            $this->db->where($where);
            $this->db->update($table);
            // 查询现有值
            $query = $this->db->select()->from($table)->where($where)->limit(1)->get();
            if ($query->row()) {
                $rs = $query->row_array();
            }else throw new Exception('L:'.__LINE__." $table query error!", 1);

            $log_arr = array(
                'action' => 'add',
                'name' => $name,
                'uid' => $uid,
                'old' => bcsub($rs[$this->object],$use_value,$dot),
                'new' => $rs[$this->object],
                'use_value' => $use_value,
                'comefrom' => isset($comefrom)?$comefrom:1,
                'source' => $source,
                'ip' => $ip,
                'add_time' => $add_time,
                'create_time' => $datetime,
                'status' => 1,
            );
            $logTb = splitTable('log_'.$this->object, $uid);
            if (!$this->log_db->insert($logTb, $log_arr)) throw new Exception('L:'.__LINE__." $logTb add insert error!", 1);
            $rs = true;
        } catch (Exception $e) {
            writeDebug('['.$datetime.'] 加'.$this->object.'失败! Err: '.$e->getMessage(), 'Doing');
        }
        return $rs;
    }


    /**
     * 扣
     * @param  array  $data_arr  [description]
     * @param  boolean $reduceMax 是否变更max_transfer
     * @param  string  $write_conn [description]
     * @return [type]              [description]
     */
    public function reduce($data_arr, $dot=2) {
        foreach ($data_arr as $key => $val) {
            $$key = $val;
        }
        unset($data_arr);
        $rs = false;
        $datetime = date('Y-m-d H:i:s');
        if(!isset($table) || $table=='') $table = 'user_info';
        if(!isset($ip) || $ip=='') $ip = '127.0.0.1';
        if(!isset($where) || $where=='') $where = array('uid'=>$uid,$this->object.'>='=>$use_value);
        try {
            $this->db->set($this->object, $this->object.'-'.$use_value, FALSE);
            // $this->db->set($this->object.'_block', $this->object.'_block+'.$use_value, FALSE);
            $this->db->where($where);
            if(!$this->db->update($table)){
                throw new Exception('L:'.__LINE__." $this->object reduce update error!", 1);
            }
            // 查询现有值
            $where = array('uid'=>$uid);
            $query = $this->db->select()->from($table)->where($where)->limit(1)->get();
            if ($query->row()) {
                $rs = $query->row_array();
            }else throw new Exception('L:'.__LINE__." $table query error!", 1);
            
            $log_arr = array(
                'action' => 'reduce',
                'name' => $name,
                'uid' => $uid,
                'old' => bcadd($rs[$this->object],$use_value,$dot),
                'new' => $rs[$this->object],
                'use_value' => $use_value,
                'comefrom' => isset($comefrom)?$comefrom:1,
                'source' => $source,
                'ip' => $ip,
                'add_time' => $add_time,
                'create_time' => $datetime,
                'status' => 1,
            );
            $logTb = splitTable('log_'.$this->object, $uid);
            if (!$this->log_db->insert($logTb, $log_arr)) throw new Exception('L:'.__LINE__." $table reduce insert error!", 1);
            $rs = true;
        } catch (Exception $e) {
            writeDebug('['.$datetime.'] 扣'.$this->object.'失败! Err: '.$e->getMessage(), 'Doing');
        }

        return $rs;
    }

    /**
     * 清用户缓存
     * @return [type] [description]
     */
    public function flushUserCache($uid){
        $CI =& get_instance();
        $default_config = array(
            'host' => '127.0.0.1',
            'port' => 6379,
            'timeout' => 0
        );
        if ($CI->config->load('redis', TRUE, TRUE)){
            $config = array_merge($default_config, $CI->config->item('redis'));
        }else{
            $config = $default_config;
        }
        $redis = new Redis();
        $redis->connect($config['host'],$config['port'],$config['timeout']);
        $redis->select(3);
        $rs = $redis->delete("USERINFO|$uid");
    }
    
}

?>